package com.sttk.secreconeclick.bookkeep.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.sttk.secreconeclick.bookkeep.BaseAc;
import com.sttk.secreconeclick.bookkeep.BaseApp;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.adapter.SaveRecordAdapter;
import com.sttk.secreconeclick.bookkeep.bean.PlanBean;
import com.sttk.secreconeclick.bookkeep.bean.SaveRecordBean;
import com.sttk.secreconeclick.bookkeep.databinding.ActivitySaveDetailBinding;
import com.sttk.secreconeclick.bookkeep.dialog.PlanDialog;
import com.sttk.secreconeclick.bookkeep.dialog.SaveMoneyDialog;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class SaveDetailActivity extends BaseAc<ActivitySaveDetailBinding> implements View.OnClickListener {

    public static int selPosition;
    private SaveRecordAdapter recordAdapter;
    private PlanBean planBean;
    private double savedMoney = 0;
    private double takenMoney = 0;
    private Calendar startCalendar = Calendar.getInstance();
    private Calendar endCalendar = Calendar.getInstance();

    private SaveMoneyDialog saveMoneyDialog;

    private static final int REQUEST_IMAGE_PICK = 1001;

    @Override
    protected int onCreate() {
        return R.layout.activity_save_detail;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSaveDetailBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());
        mDataBinding.tvEdit.setOnClickListener(this);
        mDataBinding.tvTake.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext));
        recordAdapter = new SaveRecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvEdit) {//编辑
            showPlanDialog();
        } else if (id == R.id.tvTake) {//取钱
            showSaveMoneyDialog(false);
        } else if (id == R.id.tvSave) {//存钱
            showSaveMoneyDialog(true);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        planBean = AppSpUtils.getPlanList().get(selPosition);
        updateUI();
        loadRecordData();
    }

    private void updateUI() {
        if (planBean == null) return;

        mDataBinding.tvPlanName.setText(planBean.getName());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long now = TimeUtils.string2Millis(TimeUtils.getNowString(format), format);
        long date = 0L;
        if (now >= planBean.getStartDate()) {
            date = (planBean.getEndDate() - now) / (1000 * 60 * 60 * 24); // 转换为天数
            mDataBinding.tvPlanDate.setText(getString(R.string.until_end, date));
        } else {
            date = (planBean.getStartDate() - now) / (1000 * 60 * 60 * 24); // 转换为天数
            mDataBinding.tvPlanDate.setText(getString(R.string.until_start, date));
        }

        startCalendar.setTimeInMillis(planBean.getStartDate());
        endCalendar.setTimeInMillis(planBean.getEndDate());
        mDataBinding.tvStartDate.setText(dateFormat.format(new Date(planBean.getStartDate())));
        mDataBinding.tvEndDate.setText(dateFormat.format(new Date(planBean.getEndDate())));

        calculateMoney();
        mDataBinding.tvSaveMoney.setText(String.format(Locale.getDefault(), "%.2f", savedMoney));
        mDataBinding.tvTakeMoney.setText(String.format(Locale.getDefault(), "%.2f", takenMoney));
        mDataBinding.tvPlanBudget.setText(String.format(Locale.getDefault(), "%.2f", planBean.getBudget()));
        mDataBinding.tvPlanSaveMoney.setText(String.format(Locale.getDefault(), "%.2f", (savedMoney - takenMoney)));
        updateProgress();
    }

    private void calculateMoney() {
        savedMoney = 0;
        takenMoney = 0;
        if (planBean.getRecordBeanList() != null) {
            for (SaveRecordBean record : planBean.getRecordBeanList()) {
                if (record.isSave()) {
                    savedMoney += record.getMoney();
                } else {
                    takenMoney += record.getMoney();
                }
            }
        }
    }

    private void updateProgress() {
        double totalMoney = savedMoney - takenMoney;
        int progress = (int) ((totalMoney / planBean.getBudget()) * 100);
        progress = Math.min(progress, 100);
        progress = Math.max(progress, 0);
        mDataBinding.pbPlanProgress.setProgress(progress);
    }

    private void loadRecordData() {
        if (planBean.getRecordBeanList() == null || planBean.getRecordBeanList().isEmpty()) {
            mDataBinding.tvRecordNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvRecordList.setVisibility(View.GONE);
        } else {
            mDataBinding.tvRecordNoData.setVisibility(View.GONE);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            recordAdapter.setList(planBean.getRecordBeanList());
        }
    }

    private void showPlanDialog() {
        PlanDialog dialog = new PlanDialog(mContext);
        dialog.setSelPosition(selPosition);
        dialog.setListener(new PlanDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                getData();
            }
        });
        dialog.show();
    }

    private void showSaveMoneyDialog(boolean isSave) {
        saveMoneyDialog = new SaveMoneyDialog(mContext);
        saveMoneyDialog.setSelPosition(selPosition);
        saveMoneyDialog.setSaveMode(isSave);
        saveMoneyDialog.setListener(new SaveMoneyDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                getData();
            }

            @Override
            public void clickOpenImg() {
                openImagePicker();
            }
        });
        saveMoneyDialog.show();
    }

    private void addRecord(boolean isSave, double money, String remark) {
        SaveRecordBean record = new SaveRecordBean(
                System.currentTimeMillis(),
                remark,
                money,
                "",
                isSave
        );
        if (planBean.getRecordBeanList() == null) {
            planBean.setRecordBeanList(new ArrayList<>());
        }
        planBean.getRecordBeanList().add(0, record);
        calculateMoney();
        updateUI();
        loadRecordData();
    }

    // 图片选择相关方法
    private void openImagePicker() {
        // 检查存储权限
//        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            // 请求权限
//            ActivityCompat.requestPermissions(this,
//                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
//                    1002);
//        } else {
        // 已有权限，打开图片选择器
        // 设置图片选择器活跃标识，避免返回时跳转到启动页
        BaseApp.isImagePickerActive = true;
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                saveMoneyDialog.setImg(selectedImageUri);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1002) {
            if (grantResults.length > 0) {
                // 权限被授予，打开图片选择器
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_IMAGE_PICK);
            } else {
                // 权限被拒绝
                ToastUtils.showShort("需要存储权限才能选择图片");
            }
        }
    }

}